package com.ict.start;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ict.common.FileConfigGet;
import com.ict.common.LogUtils;
import com.ict.common.TimeUtils;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

/**
 * Created by chenlong on 2017/10/9.
 * Info:
 */
public class AisPos {
    private Connection connection = null;
    private Statement statement = null;
    private ResultSet resultSet = null;
    private String Fstr;
    private String sqlStr;
    private int unixTime;
    private int xpTime;
    private FileConfigGet basic;
    private String FILEPATH;

    public FileConfigGet getBasic() {
        return basic;
    }

    public AisPos(FileConfigGet basic){
        this.basic=basic;
        FILEPATH=basic.getFileRoad()+"\\logs\\GreenGraph_DataClear.log";
//        init();
    }

    public void init(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = (Connection) DriverManager.getConnection(basic.getUrl(), basic.getUser(),basic.getPassWord());
            statement = (Statement) connection.createStatement();
        }catch (Exception e){
            System.out.println(TimeUtils.getNowTime()+ " : SQLConnection init failed"+e);
            LogUtils.LogWriteAppend(FILEPATH,TimeUtils.getNowTime()+" : SQLConnection init failed"+e);
        }
    }

    public void updateAisPos(){
        unixTime= (int) TimeUtils.getUnixTime();
//      System.out.println("当前Unix时间戳为："+unixTime);
        xpTime=unixTime-Integer.parseInt(basic.getEliTime())*3600;
//      System.out.println("消批后的时间戳为："+xpTime);

        sqlStr = "select "+basic.getTaigetidName()+","+basic.getLongitudeName()+","+basic.getLatitudeName()+" from "+basic.getTableName()+" where "+basic.getUtctimeName()+">"+xpTime;

        File file=new File(basic.fileRoad,basic.fileName);
        try{
            file.createNewFile();
        }catch(IOException e){
            e.printStackTrace();
        }

        System.out.println(TimeUtils.getNowTime()+ " : Data get start......");
        LogUtils.LogWriteAppend(FILEPATH,TimeUtils.getNowTime()+" : Data get start......");

        try {
            FileOutputStream fo=new FileOutputStream(file);
            try {
                resultSet = statement.executeQuery(sqlStr);
                while (resultSet.next()) {
//					windows下的文本文件换行符:\r\n
//					linux/unix下的文本文件换行符:\r
//					Mac下的文本文件换行符:\n
                    Fstr=resultSet.getString(basic.getTaigetidName()) + ","+resultSet.getString(basic.getLatitudeName()) + ","+resultSet.getString(basic.getLongitudeName()) + "\r\n";
//                    System.out.print(Fstr);
                    try{
                        fo.write(Fstr.getBytes());
                    }catch (Exception e){
                        System.out.println("File write Exception:"+e);
                        LogUtils.LogWriteAppend(FILEPATH,TimeUtils.getNowTime()+"File write Exception:"+e);
                    }
                }
                System.out.println(TimeUtils.getNowTime()+ " : Data get success");
                LogUtils.LogWriteAppend(FILEPATH,TimeUtils.getNowTime()+" : Data get success");
            } catch (SQLException sqlExc) {
                String sqlState=sqlExc.getSQLState();
                LogUtils.LogWriteAppend(FILEPATH,TimeUtils.getNowTime()+sqlExc);
                if("08501".equals(sqlState) || "40001".equals(sqlState)){
                    init();
                }else{
                    close();
                    sqlExc.printStackTrace();
                }
            }
        } catch (FileNotFoundException e4) {
            // TODO Auto-generated catch block
            e4.printStackTrace();
        }
    }

    /**
     * 数据的清理
     * mysql数据库里面会实时接入数据，超过指定时间段的数据会进行清理
     */
    public void clearStaleData() {
        unixTime= (int) TimeUtils.getUnixTime();
//      System.out.println("当前Unix时间戳为："+unixTime);
        xpTime=unixTime-Integer.parseInt(basic.getClearEliTime())*24*3600;
//      System.out.println("清理该时间点之前的数据："+xpTime);

        try {
            System.out.println(TimeUtils.getNowTime()+ " : Data clear start......");

            //历史数据timespacekey的清理
            sqlStr = "DELETE from l1_target_history_positions_TimeSpaceKey_2017 WHERE Record_UTC_Time<"+xpTime;
            statement.execute(sqlStr);

            //历史数据shipidkey的清理
            sqlStr = "DELETE from l1_target_history_positions_ShipIDKey_2017 WHERE Record_UTC_Time<"+xpTime;
            statement.execute(sqlStr);

            //实时表数据的清理
            sqlStr = "DELETE from l1_target_last_position WHERE Record_UTC_Time<"+xpTime;
            statement.execute(sqlStr);

            //进离港数据的清理
            sqlStr = "DELETE from ship_ioevent WHERE event_time_UTC<"+xpTime;

            System.out.println(TimeUtils.getNowTime()+ " : Data clear success");

        }catch (Exception e){
            System.out.println(TimeUtils.getNowTime()+ " : Data clear failed");
            close();
            e.printStackTrace();
        }
    }

    public void close(){
        try {
            resultSet.close();
        } catch (Exception e3) {
            e3.printStackTrace();
        }
        try {
            statement.close();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        try {
            connection.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        close();
    }
}
